<template>
	<div class="space"></div>

	<van-form @submit="onSubmit">
		<van-field v-model="business.email" label="邮箱" readonly />
		<van-field v-model="code" center clearable label="邮箱验证码" placeholder="请输入邮箱验证码">
			<template #button>
				<van-button size="small" type="primary" :disabled="btnDisabled" @click="sendCode">{{
					btnText
				}}</van-button>
			</template>
		</van-field>

		<div style="margin: 16px">
			<van-button round block type="primary" :disabled="!code" native-type="submit"> 提交 </van-button>
		</div>
	</van-form>
</template>

<script setup>
import { getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();

// 会员数据
const business = proxy.$cookies.get('business');

if (!business.email) {
	proxy.$message('您的邮箱地址为空，请先设置邮箱');
	proxy.$router.back();
}

const code = ref('');
const btnText = ref('发送验证码');
const btnDisabled = ref(false);
const num = ref(59);

const sendCode = async () => {
	btnDisabled.value = true;

	btnText.value = `发送验证码(${60})`;

	const timer = setInterval(() => {
		btnText.value = `发送验证码(${num.value--})`;
		if (num.value <= 0) {
			clearInterval(timer);
			btnDisabled.value = false;
			num.value = 59;
			btnText.value = '发送验证码';
		}
	}, 1000);

	const data = {
		id: business.id,
		action: 'send',
	};

	const res = await proxy.$POST({
		url: '/business/email',
		params: data,
	});

	if (res.code === 0) {
		proxy.$fail(res.msg);
		// 发送失败重置时间
		clearInterval(timer);
		btnDisabled.value = false;
		num.value = 59;
		btnText.value = '发送验证码';
		return false;
	}

	proxy.$success({
		message: res.msg,
		duration: 1000,
	});
};

const onSubmit = async () => {
  const data = {
		id: business.id,
		code: code.value,
	};

	const res = await proxy.$POST({
		url: '/business/email',
		params: data,
	});

	if (res.code === 0) {
		proxy.$fail(res.msg);
		return false;
  }

  proxy.$router.push('/business/index');

	proxy.$success({
		message: res.msg,
		duration: 1000,
	});
};
</script>

<style scoped></style>
